import { Modal, Button, List, Avatar, message } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { chainConfig, type ChainItemType } from "@/utils/wallet-util";
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { useProviderHook } from "@/utils/hooks.tsx";
import type { RootState } from "@/store";
import { setChainId, setNativeSymbol, updateBalance } from "@/store/slices/walletSlice";
import { ethers } from "ethers";
interface SwitchChainProps {
  setOpen: (val: boolean) => void
}
const switchChain = forwardRef((props: SwitchChainProps, ref) => {
  const walletState = useAppSelector((state: RootState) => state.wallet);
  const { setProvider } = useProviderHook()
  const [chainList, setChainList] = useState<ChainItemType[]>([])
  const dispatch = useAppDispatch();
  const [open, setOpen] = useState(false)
  useEffect(() => {
    setChainList(Object.values(chainConfig))
  }, [])
  useImperativeHandle(ref, () => ({
    setOpen
  }))
  const changeChain = async (chain: ChainItemType) => {
    dispatch(setNativeSymbol(chain.nativeCurrency.symbol));
    dispatch(setChainId(chain.chainId));
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    setProvider(provider)
    message.success(`切换到${chain.chainName}网络成功`)
    props.setOpen(false)
  }
  return (
    <Modal
      title="切换网络"
      open={open}
      footer={null}
      onCancel={() => setOpen(false)}
    >
      <List
        dataSource={chainList}
        renderItem={(chain) => (
          <List.Item
            actions={[
              <Button 
                key="connect" 
                type="primary" 
                onClick={async () => {
                  try {
                    await window.ethereum.request({
                      method: "wallet_switchEthereumChain",
                      params: [{ chainId: chain.chainId }],
                    });
                    changeChain(chain)
                  } catch (error) {
                    if ((error as any).code == '4902') {
                      await window.ethereum.request({
                        method: "wallet_addEthereumChain",
                        params: [chain],
                      });
                      await window.ethereum.request({
                        method: "wallet_switchEthereumChain",
                        params: [{ chainId: chain.chainId }],
                      });
                      changeChain(chain)
                    }
                  }
                }}
              >
                切换
              </Button>
            ]}
          >
            <List.Item.Meta
              avatar={<Avatar shape='square'>{ chain.nativeCurrency.symbol }</Avatar>}
              title={chain.chainName}
            />
          </List.Item>
        )}
      />
    </Modal>
  );
})

export default switchChain